package org.base.common.util;


import org.base.common.token.JWTToken;

import java.util.function.Function;

public class UserUtils {

    private static final ThreadLocal<JWTToken> tokenHolder = new InheritableThreadLocal();

    /**
     * 获取当前登录用户id
     */
    public static Long getUserId() {
        return get(JWTToken::getUserId);
    }

    /**
     * 获取当前登录用户名称
     */
    public static String getUserName() {
        return get(JWTToken::getUserName);
    }

    private static <T, R> R get(Function<JWTToken, R> func) {
        final JWTToken jwtToken = tokenHolder.get();
        if (jwtToken != null) {
            return func.apply(jwtToken);
        }
        return null;
    }


    public static void set(JWTToken token) {
        tokenHolder.set(token);
    }

    public static void remove() {
        tokenHolder.remove();
    }
}
